package com.example.tingshu.service;

import com.example.tingshu.dao.UserDao;
import com.example.tingshu.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class UserService {
    private final UserDao userDao;

    @Autowired
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User login(String username, String password){
        password = sha512(password);

        return userDao.selectOneByUsernameAndPassword(username,password);
    }

    private String sha512(String plainText){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
            byte[] bytes = plainText.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest){
                sb.append(String.format("%02x",b));
            }
            return sb.toString();
        }catch (NoSuchAlgorithmException | UnsupportedEncodingException e){
            throw new RuntimeException();
        }
    }
}
